package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    public static final String IMG_KEY = "MEAL_IMG";
    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(Integer id){
        Setmeal setmeal = setMealService.findById(id);

        return new Result(setmeal!=null?true:false,setmeal!=null? MessageConstant.QUERY_SETMEAL_SUCCESS:MessageConstant.QUERY_SETMEAL_FAIL,setmeal);
    }

    /**
     * 新增体检套餐
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,@RequestParam List<Integer> checkgroupIds){
        boolean  temp = setMealService.add(setmeal,checkgroupIds);
        return new Result(temp,temp?MessageConstant.ADD_SETMEAL_SUCCESS:MessageConstant.ADD_SETMEAL_FAIL);
    }

    /**
     * 编辑
     * @param setmeal
     * @param checkGroupIds
     * @return
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody Setmeal setmeal,@RequestParam List<Integer> checkGroupIds){
        log.info("修改套餐：{},{}",setmeal,checkGroupIds);
        boolean temp = setMealService.edit(setmeal,checkGroupIds);
        return new Result(temp,temp?MessageConstant.EDIT_SETMEAL_SUCCESS:MessageConstant.EDIT_SETMEAL_FAIL);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setMealService.findPage(queryPageBean);
    }

    /**
     * 上传照片
     * @param imgFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile) throws IOException {
        log.info("文件上传:{}",imgFile);
        //原始文件名
        String originalName = imgFile.getOriginalFilename();
        //截取原始文件名的后缀,
        String extension = originalName.substring(originalName.lastIndexOf("."));
        String name= UUID.randomUUID().toString()+extension;
        String filepath = aliOssUtil.upload(imgFile.getBytes(),name);
        //向redis key为IMG_KEY 加入文件路径
        redisTemplate.opsForValue().append(IMG_KEY,filepath);
        return new  Result(true,MessageConstant.UPLOAD_SUCCESS,filepath);

    }




    /**
     * 开启定时删除照片.每天上午10点开始删除redis 照片
     */
    @Scheduled(cron = "0 0 10 * * ? ")
    public void execute(){
        //1。获取数据库的照片路径
        List<String> listImg = setMealService.getImgs();
        //2.获取redis 中的照片路径
        String keys = (String) redisTemplate.opsForValue().get(IMG_KEY);
        System.out.println("2:"+keys);

        String regex = "https://web-9991\\.oss-cn-hangzhou\\.aliyuncs\\.com/\\w+-\\w+-\\w+-\\w+-\\w+\\.jpg";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(keys);
        // 使用 Set 存储唯一的 URL
        Set<String> urlSet = new HashSet<>();

        // 提取所有匹配的 URL 并添加到 Set 中
        while (matcher.find()) {
            urlSet.add(matcher.group());
        }
        // 3.计算差集
        Set<String> intersection = new HashSet<>(urlSet); // 复制 item1
        intersection.retainAll(listImg);



        Set<String> difference = new HashSet<>(urlSet); // 复制 item1
        difference.removeAll(intersection);
        //删除阿里云中多余照片

        difference.forEach(s -> {
            String regex1 = "([\\w-]+\\.jpg)";

            Pattern pattern1 = Pattern.compile(regex1);
            Matcher matcher1 = pattern1.matcher(s);
            aliOssUtil.delete(matcher1.group());
        });
        //删除redis 的数据
        redisTemplate.delete(IMG_KEY);


    }


}
